package com.rainsoftware.LicenseSystem.controllers.api;

import com.rainsoftware.LicenseSystem.services.AuthService;
import com.rainsoftware.LicenseSystem.utils.StandardResponse;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/auth")
public class AuthController {

    @Autowired
    private AuthService authService;

    @PostMapping("/register")
    public ResponseEntity<String> onRegister(@RequestParam(required = false) String username,
                                             @RequestParam(required = false) String password,
                                             @RequestParam(required = false) String email,
                                             @RequestBody(required = false) String jsonBody) {
        if (jsonBody != null) {
            JSONObject json = new JSONObject(jsonBody);
            username = json.optString("username");
            password = json.optString("password");
            email = json.optString("email");
        }
        StandardResponse response = authService.register(username, password, email);
        return response.build();
    }

    @PostMapping("/login")
    public ResponseEntity<String> onLogin(@RequestParam(required = false) String username,
                                          @RequestParam(required = false) String password,
                                          @RequestBody(required = false) String jsonBody) {
        if (jsonBody != null) {
            JSONObject json = new JSONObject(jsonBody);
            username = json.optString("username");
            password = json.optString("password");
        }
        StandardResponse response = authService.login(username, password);
        return response.build();
    }
}